<template>
    <div id="login">
        <el-form label-width="80px" label-position="right" 
        ref="loginFormRef"
        :rules="rules"
        :model="loginForm"
        status-icon>
            <el-form-item label="用户名" prop="username">
                <el-input type="text" v-model="loginForm.username"/>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input  type="password" v-model="loginForm.password"/>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="doLogin">登录</el-button>
                <el-button type="warning" @click="clear">清空数据</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
  
<script>
import {sha256} from 'js-sha256'
import {mapActions} from 'vuex'
export default{
    data(){
        return {
            loginForm:{
                username:"",
                password:""
            },
            rules:{
                username:[
                    {required:true,message:"用户名不能为空",trigger:"blur"},
                    {min:3,max:20,message:"用户名长度为3-20个字符",trigger:"blur"}
                ],
                password:[
                    {required:true,message:"密码不能为空",trigger:"blur"},
                    {min:3,max:20,message:"密码长度为3-20个字符",trigger:"blur"}
                ]
            }
        }
    },
    methods:{
        ...mapActions({
            asyncLogin:"userStore/asyncLogin",
            getPermission:"userStore/getPermission"
        }),
        doLogin(){
            if(!this.$refs.loginFormRef) return; //判断ref没有绑定成功
            this.$refs.loginFormRef.validate(async (ispass,field)=>{
                if(ispass){
                    // quxue账号密码 被加密了   新增的用户没有加密
                    let password =this.loginForm.username=='quxue'?sha256(this.loginForm.password):this.loginForm.password;
                    let loginData={...this.loginForm,password}
                    await this.asyncLogin(loginData);
                    await this.getPermission();
                }else{
                    console.log("验证未通过!",field)
                }
            })
        },
        clear(){

        }
    }
}
</script>
<style lang="scss" scoped>
#login{
    width:300px;
    position: absolute;
    left:50%;
    top:50%;
    transform: translate(-50%,-50%);
}
:deep(.el-form-item__label::before){
    content:"*" !important;
}
</style>